<template>
  <div>
    <div class="control-group-page">
      <!-- aside -->
      <div class="manage-page-aside">
        <div class="head-section">
          <h3 class="table-head">网点管理</h3>
        </div>
        <div class="table-section">

          <el-table ref="refGroupTable" :data="groupTableData" border highlight-current-row
            :row-class-name="tableRowClassName" @row-click="handleCurrentChange" height="7.5rem">
            <el-table-column type="index" label="序号" width="60">
            </el-table-column>
            <el-table-column prop="name" label="网点名称" style="cursor: pointer">
            </el-table-column>
            <el-table-column label="编辑操作" width="120">
              <template slot-scope="scope">
                <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>

        </div>
      </div>
      <!-- content -->
      <div class="content manage-page-content">
        <div class="head-section">
          <header>
            <!-- <el-button @click="FileListshow=!FileListshow" v-show="!FileListshow" size="medium" type="primary" plain>文件列表
            </el-button>
            <el-button @click="FileListshow=!FileListshow" v-show="FileListshow" size="medium" type="primary" plain>用户配置
            </el-button> -->
            <el-button @click="handleAddUserOrganRePort" v-if="groupId !=null && listType==1" size="medium" type="primary" plain>添加
            </el-button>
            <el-button @click="handleDeleteUserOrganRePort" v-if="groupId !=null && listType==1" size="medium" type="primary" plain>移除
            </el-button>
             <el-button @click="handleAddUserOrganWechat" v-if="groupId !=null && listType==2" size="medium" type="primary" plain>添加
            </el-button>
            
          </header>
          <h3>
            <el-button @click="listType=1" :plain="listType!=1" type="primary">用电量报表邮箱推送用户</el-button>
            <el-button @click="listType=2" :plain="listType!=2" type="primary">微信设备告警用户</el-button>
            <el-button @click="listType=3" :plain="listType!=3" type="primary">用电量报表文件列表</el-button>
          </h3>
        </div>
        <div v-show="listType==1" class="table-section">
          <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100%">
            <el-table :data="userrepothData" ref="userrepothTable" @selection-change="handleUserrepothChange" border
              style="width: 100%; margin-top: 10px">
              <el-table-column type="selection" width="40"> </el-table-column>
              <el-table-column type="index" label="序号" width="50">
              </el-table-column>
              <el-table-column prop="userName" label="用户名"> </el-table-column>
              <el-table-column prop="userMail" label="用户邮箱"> </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>
         <div v-show="listType==2" class="table-section">
          <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100%">
            <el-table :data="userrepothWechatData" ref="userrepothWechatTable" border
              style="width: 100%; margin-top: 10px">
           
              <el-table-column type="index" label="序号" width="50">
              </el-table-column>
              <el-table-column prop="name" label="用户名"> </el-table-column>
              <el-table-column prop="phone" label="接收手机"> </el-table-column>
              <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button type="primary" size="small" @click="handleDel(scope.row)">移除</el-button>
              </template>
            </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>
        <div  v-show="listType==3" class="table-section">
          <el-scrollbar wrap-class="scrollbar-wrapper" style="height: 100%">
            <el-table :data="FileListdata" ref="FileListTable" border
              style="width: 100%; margin-top: 10px">
              <el-table-column type="selection" width="40"> </el-table-column>
              <el-table-column type="index" label="序号" width="50">
              </el-table-column>
              <el-table-column prop="name" label="文件名"> </el-table-column>
              <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <el-button type="primary" size="small" @click="handleDown(scope.row)">下载</el-button>
              </template>
            </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>
      </div>
    </div>
    <!-- 添加设备 -->
    <el-dialog title="用电量报表邮箱推送用户" :visible.sync="dialogAddUserOrganRePortVisible" width="610px" @close="reGetUserBindData"
      :close-on-click-modal="false">
      <div style="margin-bottom:10px">
        <span style="color:#fff;margin-right:10px">用户邮箱</span>
        <el-select clearable @change="changeusermail" v-model="usermail" filterable  allow-create default-first-option
          placeholder="请填写用户邮箱">
          <el-option v-for="item in userData" :key="item.id" :label="item.name +'-'+item.email" :value="item.email">
          </el-option>
        </el-select>
        <!-- <el-select @change="areaChangeEvent" filterable v-model="areaid" placeholder="请选择" value-key="item">
          <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select> -->
      </div>

      <div slot="footer" class="dialog-footer">
        <div class="sub-can-btn-box">
          <el-button @click="submitAddUserOrganRePort" size="medium" type="primary">确 定
          </el-button>
          <el-button size="medium" @click="dialogAddUserOrganRePortVisible = false">取 消
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 添加设备 -->
    <el-dialog title="微信报警推送用户" :visible.sync="dialogAddUserOrganWechatVisible" width="610px" @close="reGetUserBindWechatData"
      :close-on-click-modal="false">
      <div style="margin-bottom:10px">
        <span style="color:#fff;margin-right:10px">用户手机</span>
        <el-select clearable @change="changeuserphone" v-model="userphone" filterable  default-first-option
          placeholder="请填写用户手机">
          <el-option v-for="item in userData" :key="item.id" :label="item.name +'-'+item.phone" :value="item.phone">
          </el-option>
        </el-select>
        <!-- <el-select @change="areaChangeEvent" filterable v-model="areaid" placeholder="请选择" value-key="item">
          <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select> -->
      </div>

      <div slot="footer" class="dialog-footer">
        <div class="sub-can-btn-box">
          <el-button @click="submitAddUserOrganWechatRePort" size="medium" type="primary">确 定
          </el-button>
          <el-button size="medium" @click="dialogAddUserOrganWechatVisible = false">取 消
          </el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog class="same-dia" title="修改网点配置" @close="closeorganModify('organform')" :visible.sync="dialogorganVisible"
      width="400px" center :close-on-click-modal="false">
      <el-form label-width="100px" :rules="rules" ref="organform" :model="organform">

        <el-form-item label="邮箱：" prop="acceptMail">
          <el-input v-model="organform.acceptMail"></el-input>
        </el-form-item>
        <el-form-item label="邮箱服务器" prop="acceptMailHost">
          <el-input v-model="organform.acceptMailHost" style="width:200px"></el-input>
          <el-tooltip class="item" effect="dark" content="" placement="right">
            <div slot="content">请填写邮箱服务器地址 @ 后面信息为服务器地址，</br>以QQ邮箱为例：如xxxx@qq.com 邮箱服务器地址即为qq.com</div>
            <i class="el-icon-warning-outline" style="color: #fff;font-size: 20px;margin-left: 10px;"></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="邮箱授权码" prop="acceptMailCode">
          <el-input v-model="organform.acceptMailCode" style="width:200px"></el-input>
          <el-tooltip class="item" effect="dark" content="请填写邮箱授权码" placement="right">
            <i class="el-icon-warning-outline" style="color: #fff;font-size: 20px;margin-left: 10px;"></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="推送邮件" prop="reportTask">
          <el-switch :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949"
            v-model="organform.reportTask"></el-switch>
          <el-tooltip class="item" effect="dark" content="每日8：00推送每日用电量数据报表至邮箱" placement="right">
            <i class="el-icon-warning-outline" style="color: #fff;font-size: 20px;margin-left: 10px;"></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="中控屏锁屏" prop="screenLock">
          <el-switch :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949"
            v-model="organform.screenLock"></el-switch>
          <el-tooltip class="item" effect="dark" content="中控大屏长时间无操作是否锁屏" placement="right">
            <i class="el-icon-warning-outline" style="color: #fff;font-size: 20px;margin-left: 10px;"></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item class="sub-can-btn-box">
          <el-button type="primary" @click="submitorganModify('organform')">确定
          </el-button>
          <el-button @click="dialogorganVisible=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import ajax from "@/utils/ajax";
import { tableSelection, deleteConfirm } from "@/utils/elementui.js";
import axios from "axios";
export default {
  data() {
    return {
      //用户公司
      groupTableData: [],
      groupId: null,
      tableIndex: 0,
      currentGroup: null,
      //已配置用户
      userrepothData: [],
      //添加推送用户
      dialogAddUserOrganRePortVisible: false,
      AlluserData: [],
      userData: [],
      usermail: "",
      userId: null,
      userName: "",
      organform: {
        acceptMail: "",
        acceptMailCode: "",
        acceptMailHost: "",
        address: "",
        customerId: 0,
        hostNum: 0,
        name: "",
        probeMun: 0,
        probeStatistics: {},
        reportTask: 0,
        screenLock: 0,
      },
      rules: {
        acceptMail: [
          { required: true, message: "电子邮箱不能为空", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
      },
      dialogorganVisible: false,
      UserrepothSelection: [],
      FileListdata: [],
       //已配置用户
      userrepothWechatData: [],
      listType: 1,
      dialogAddUserOrganWechatVisible:false,
      userphone:""
    };
  },
  created() {
    this.customerId = this.$store.getters.customerId;
  },
  mounted() {
    this.$store.dispatch("actions/dynamicTitleAction", this.$route.meta.title);
    this.getOrganByCustomdata();
    this.getUserListData();
  },

  methods: {
    // 获取用户列表
    getUserListData() {
      let pocustomerId = this.customerId;
      ajax.get({
        url: this.$API.getUserListByCustomerId + pocustomerId,

        success: (response) => {
          //console.log(response)
          if (response.data) {
            this.AlluserData = response.data.filter((data) => data.email != "");
          }
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    //获取客户公司下的网点
    getOrganByCustomdata() {
      ajax.get({
        url: this.$API.getOrganByCustomId + this.customerId,
        success: (response) => {
          this.groupTableData = response.data;
          if (response.data.length > 0) {
            this.$nextTick(() => {
              let index = this.tableIndex;
              this.$refs.refGroupTable.setCurrentRow(
                this.$refs.refGroupTable.data[index]
              );
              this.currentGroup = response.data[index];
              this.groupId = response.data[index].id;
              this.getOrganReportTaskUserList();
              this.getUserListWithOrganWechatTarget()
              this.getFileList();
            });
          } else {
            this.AreaAppliancesData = [];
          }
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 点击公司行
    handleCurrentChange(row) {
      this.currentGroup = row;
      this.groupId = row.id;
      this.tableIndex = row.index;
      this.$nextTick(() => {
        this.getOrganReportTaskUserList();
        this.getUserListWithOrganWechatTarget()
        this.getFileList();
      });
    },
    //获取网点邮箱配置用户
    getOrganReportTaskUserList() {
      let po_id = this.groupId;
      ajax.get({
        url: this.$API.getOrganReportTaskUserList + po_id,
        // data: { id: po_id },
        success: (response) => {
          const resp = response.data;
          this.userrepothData = resp;
        },
      });
    },
    //获取网点微信配置用户
    getUserListWithOrganWechatTarget() {
      let po_id = this.groupId;
      ajax.get({
        url: this.$API.getUserListWithOrganWechatTarget + po_id,
        // data: { id: po_id },
        success: (response) => {
          const resp = response.data;
          this.userrepothWechatData = resp;
        },
      });
    },
    //获取网点文件列表
    getFileList() {
      let po_id = this.groupId;
      ajax.get({
        url: this.$API.getFileList + po_id,
        // data: { id: po_id },
        success: (response) => {
          const resp = response.data;
          this.FileListdata = resp;
        },
      });
    },
    // 重新获取绑定区域的数据
    reGetUserBindData() {
      if (this.groupId != null) {
        this.getOrganReportTaskUserList();
        this.userId = null;
        this.usermail = "";
        this.userName = "";
      }
    },
    //改变邮箱
    changeusermail(value) {
      let self = this;

      let inuser = this.userrepothData.findIndex(
        (data) => data.userMail == value
      );
      let allinuser = this.AlluserData.findIndex((data) => data.email == value);
      console.log(inuser, allinuser);

      if (inuser != -1) {
        self.$message({
          message: "已添加用户",
          type: "error",
        });
        this.userMail = "";
      } else if (allinuser == -1) {
        this.userId = -1;
        this.userName = "";
      } else {
        this.userName = this.AlluserData[allinuser].name;
        this.userId = this.AlluserData[allinuser].id;
      }
    },
    //提交
    submitAddUserOrganRePort() {
      let self = this;
      let reg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
      if (!reg.test(this.usermail)) {
        self.$message({
          message: "请检查邮箱格式是否正确",
          type: "error",
        });
        return;
      }
      if (
        this.userrepothData.findIndex(
          (data) => data.userMail == this.usermail
        ) != -1
      ) {
        self.$message({
          message: "已添加用户",
          type: "error",
        });
        return;
      }
      let attr = [];
      let data = {};
      data.organId = this.groupId;
      data.userId = this.userId;
      data.userMail = this.usermail;
      data.userName = this.userName;
      attr.push(data);
      ajax.post({
        url: this.$API.setOrganReportTaskUserList,
        data: attr,
        success: (response) => {
          this.dialogAddUserOrganRePortVisible = false;
        },
      });
    },
    // 选择用户
    handleUserrepothChange(value) {
      this.UserrepothSelection = value;
    },

    // 添加用户弹窗
    handleAddUserOrganRePort() {
      if (this.userrepothData.length > 0) {
        this.userData = this.AlluserData;
      } else {
        //console.log(2)
        this.userData = this.AlluserData;
      }
      this.dialogAddUserOrganRePortVisible = true;
    },
    handleDeleteUserOrganRePort() {
      let self = this;
      let selectionArr = this.UserrepothSelection;
      let selResult = tableSelection(selectionArr, 0);
      if (selResult) {
        let idsArr = [];
        for (let item of selectionArr) {
          idsArr.push(item.id);
        }

        axios.post(this.$API.deleteReportTaskUser, idsArr).then(function (res) {
          if (res.data.success) {
            self.$message({
              message: "删除成功",
              type: "success",
            });
            self.getOrganReportTaskUserList();
          }
        });
      }
    },
    //处理复选框选中
    checkValue(targetCategoryIds, targetCategoryDataId) {
      if (targetCategoryIds == "0") {
        return true;
      }
      if (targetCategoryIds.indexOf(targetCategoryDataId) !== -1) {
        return true;
      }
    },

    // table每行加上index
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },
    handleEdit(row) {
      console.log(row);
      this.organform = row;
      this.dialogorganVisible = true;
    },
    handleDown(row) {
      console.log(row);
      window.open(this.$API.getFile + `/${this.groupId}/${row.name}`, "_blank");
    },
    submitorganModify(formName) {
      let self = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          ajax.post({
            url: this.$API.upDataOrgan + this.organform.id,
            data: this.organform,
            success: (response) => {
              self.$message({
                message: "编辑成功",
                type: "success",
              });
              self.dialogorganVisible = false;
              self.getOrganByCustomdata();
            },
          });
        }
      });
    },

    closeorganModify(formName) {
      //this.$refs[formName].resetFields();
    },
// 添加用户弹窗
    handleAddUserOrganWechat() {
      if (this.userrepothData.length > 0) {
        this.userData = this.AlluserData;
      } else {
        //console.log(2)
        this.userData = this.AlluserData;
      }
      this.dialogAddUserOrganWechatVisible = true;
    },
    //改变手机
    changeuserphone(value) {
      let self = this;

      let inuser = this.userrepothData.findIndex(
        (data) => data.userphone == value
      );
      let allinuser = this.AlluserData.findIndex((data) => data.phone == value);
      console.log(inuser, allinuser);

      if (inuser != -1) {
        self.$message({
          message: "已添加用户",
          type: "error",
        });
        this.userphone = "";
      } else if (allinuser == -1) {
        this.userId = -1;
        this.userName = "";
      } else {
        this.userName = this.AlluserData[allinuser].name;
        this.userId = this.AlluserData[allinuser].id;
      }
    },
    reGetUserBindWechatData() {
      if (this.groupId != null) {
        this.getUserListWithOrganWechatTarget();
        this.userId = null;
        this.userphone = "";
      }
    },
    //提交
    submitAddUserOrganWechatRePort() {
      let self = this;
      let reg = /^1[3-9][0-9]{9}$/;
      if (!reg.test(this.userphone)) {
        self.$message({
          message: "请检查手机是否正确",
          type: "error",
        });
        return;
      }
      if (
        this.userrepothWechatData.findIndex(
          (data) => data.phone == this.userphone
        ) != -1
      ) {
        self.$message({
          message: "已添加用户",
          type: "error",
        });
        return;
      }
      
      let data = {};
      data.organId = this.groupId;
      data.userId = this.userId;
      data.telephone = this.userphone;
      ajax.post({
        url: this.$API.addOrganWechatTarget,
        data: data,
        success: (response) => {
          this.dialogAddUserOrganWechatVisible = false;
        },
      });
    },
     // 删除组
    handleDel(data) {
      deleteConfirm(this).then((res) => {
          if (res) {
            ajax.post({
              url: this.$API.removeOrganWechatTarget + `${this.groupId}/${data.id}/${data.phone}`,
              success: (response) => {
                if (response.success) {
                 
                  this.getUserListWithOrganWechatTarget();
                  this.$message({
                    message: response.message,
                    type: "success",
                  });
                }
              },
              error: (response) => {
                this.$message({
                  message: response.message,
                  type: "error",
                });
              },
            });
          }
        });
    },

  },
};
</script>

<style lang="stylus" scoped>
>>> {
  .control-group-page {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 0.2rem;
    overflow: auto;

    .head-section {
      .table-head {
        /* margin-top 0.2rem */
        height: 0.43rem;
        line-height: 0.43rem;
        font-size: 0.16rem;
        font-weight: normal;
        float: left;
      }

      header {
        float: right;
      }
    }

    .table-section {
      position: absolute;
      top: 0.72rem;
      left: 0.2rem;
      right: 0.2rem;
      bottom: 0.2rem;
    }

    .content {
      .content-head {
        text-align: right;
      }

      .area-table-section {
        position: absolute;
        top: 0.66rem;
        left: 0.2rem;
        right: 0.2rem;
        bottom: 0.2rem;
      }
    }
  }

  .dialog-left {
    .table-head {
      height: 0.3rem;
      margin-top: 0.2rem;
      font-size: 0.16rem;
      font-weight: normal;
    }

    .table-section {
      position: absolute;
      top: 1.2rem;
      left: 0.2rem;
      right: 0.2rem;
      bottom: 0.2rem;
    }

    .dia-table-section {
      height: 300px;
    }
  }

  .el-table__body tr {
    cursor: pointer;
  }

  .el-table--striped .el-table__body tr.el-table__row--striped.current-row td, .el-table__body tr.current-row > td {
    color: #fff;
    background-color: rgba(68, 199, 244, 0.2) !important;
  }

  .el-table__body-wrapper {
    overflow-y: auto !important;
  }

  .el-table .el-checkbox__label {
    color: #fff;
  }

  .el-button.is-round {
    padding: 3px 6px;
  }

  .temperature-txt {
    padding: 0 0.1rem;
    font-size: 0.16rem;
    color: #fff;
  }

  .el-select--mini {
    width: 60px;

    .el-input--suffix .el-input__inner {
      padding-right: 20px;
      padding-left: 10px;
    }
  }

  .air-table-item {
    margin-right: 0.1rem;
  }

  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner, .el-radio__input.is-disabled.is-checked .el-radio__inner {
    background: #409EFF;
  }

  .el-button {
    padding: 0.12rem 0.16rem;
  }

  .el-dialog__footer {
    padding-top: 0;
    padding-bottom: 0.3rem;
  }

  .el-form-item:last-child {
    margin-bottom: 0 !important;
  }

  .area-add {
    width: 380px;
    margin: 0 auto;

    .el-select {
      width: 300px;
    }
  }
}

>>>.el-table--striped .el-table__body tr.el-table__row--striped.current-row td, >>>.el-table__body tr.current-row > td {
  color: #fff;
  background-color: rgba(68, 199, 244, 0.2) !important;
}

.e-t-r-rule-box {
  display: flex;
}

.left, .right {
  width: 360px;
  height: 8.1rem;
  padding: 10px;
  border: 1px solid #fff;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.dialog-group-btn {
  width: 200px;
  padding: 0.2rem;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.dialog-group-btn .el-button {
  display: block;
  margin: 0.2rem auto;
}

.dialogrule_worktype .el-radio {
  margin-bottom: 10px;
}
</style>
